import React, { useState } from 'react';
import { Form, Input, Button, Card, Typography, Space, Spin, Alert } from 'antd';
import { UserOutlined, LockOutlined, LoginOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAppContext } from '../contexts/AppContext';
import { authService } from '../services/auth';
import { LoginRequest } from '../types';
import './Login.css';

const { Title, Text } = Typography;

const Login: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string>('');
  const navigate = useNavigate();
  const { login, showSuccess, showError } = useAppContext();

  const handleLogin = async (values: LoginRequest) => {
    setLoading(true);
    setError('');

    try {
      const response = await authService.login(values);
      
      if (response.code === 200 && response.data) {
        login(response.data.user);
        showSuccess('登录成功', `欢迎回来，${response.data.user.username}！`);
        navigate('/dashboard');
      } else {
        setError(response.message || '登录失败');
      }
    } catch (error: any) {
      const errorMessage = error.response?.data?.message || error.message || '登录失败，请重试';
      setError(errorMessage);
      showError('登录失败', errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const handleFormValuesChange = () => {
    if (error) {
      setError('');
    }
  };

  return (
    <div className="login-container">
      <div className="login-background">
        <div className="login-card-wrapper">
          <Card className="login-card" bordered={false}>
            <div className="login-header">
              <Space direction="vertical" size="large" align="center">
                <div className="login-logo">
                  <LoginOutlined style={{ fontSize: '48px', color: '#1890ff' }} />
                </div>
                <Title level={2} style={{ margin: 0, color: '#001529' }}>
                  DCarpai Guider
                </Title>
                <Text type="secondary" style={{ fontSize: '16px' }}>
                  懂车拍管理平台
                </Text>
              </Space>
            </div>

            {error && (
              <Alert
                message="登录失败"
                description={error}
                type="error"
                showIcon
                closable
                onClose={() => setError('')}
                style={{ marginBottom: 24 }}
              />
            )}

            <Form
              form={form}
              name="login"
              size="large"
              onFinish={handleLogin}
              onValuesChange={handleFormValuesChange}
              autoComplete="off"
            >
              <Form.Item
                name="username"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { min: 2, message: '用户名至少2个字符' },
                ]}
              >
                <Input
                  prefix={<UserOutlined />}
                  placeholder="请输入用户名"
                  autoComplete="username"
                />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 6, message: '密码至少6个字符' },
                ]}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="请输入密码"
                  autoComplete="current-password"
                />
              </Form.Item>

              <Form.Item style={{ marginBottom: 0 }}>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  block
                  size="large"
                  icon={<LoginOutlined />}
                >
                  {loading ? '登录中...' : '登录'}
                </Button>
              </Form.Item>
            </Form>

            <div className="login-footer">
              <Space direction="vertical" size="small" align="center">
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  测试账号：admin / admin123
                </Text>
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  © 2025 DCarpai Team. All rights reserved.
                </Text>
              </Space>
            </div>
          </Card>
        </div>
      </div>

      {loading && (
        <div className="login-loading-overlay">
          <Spin size="large" tip="正在登录..." />
        </div>
      )}
    </div>
  );
};

export default Login;
